package cn.tedu.boot.demo.service.impl;

import cn.tedu.boot.demo.dto.AdminAddNewDTO;
import cn.tedu.boot.demo.entity.Admin;
import cn.tedu.boot.demo.ex.ServiceException;
import cn.tedu.boot.demo.mapper.AdminMapper;
import cn.tedu.boot.demo.service.IAdminService;
import cn.tedu.boot.demo.utils.GlobalPasswordEncoder;

import cn.tedu.boot.demo.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void addNew(AdminAddNewDTO adminAddNewDTO) {
        //判断参数adminAddNewDTO中的username,调用AdminMapper的Admin getByUsername(String username)执行查询,并获取查询结果
        log.debug("即将增加管理员:{}",adminAddNewDTO);
        String username = adminAddNewDTO.getUsername();
        Admin queryResult = adminMapper.getByUsername(username);
        //判断查询结果是否[不为null]
        if (queryResult != null) {
            //--是:表示用户名已经被占用,抛出ServiceException:增加管理员失败,用户名已经被占用
            log.warn("增加管理员失败,用户名({})已经被占用!",username);
            throw new ServiceException(JsonResult.State.ERR_CONFLICT,"增加管理员失败,用户名已经被占用");
        }

        //  以参数adminAddNewDTO中的password作为明文,执行加密,得到密文密码
        String rawPassword = adminAddNewDTO.getPassword();
        String encodePassword = passwordEncoder.encode(rawPassword);
        //创建新的Admin对象
        Admin admin = new Admin();
        //为Admin对象的属性赋值:username,nickname来自参数adminAddNewDTO
        admin.setUsername(username);
        admin.setNickname(adminAddNewDTO.getNickname());
        // 为Admin对象的属性赋值:password >密文密码
        admin.setPassword(encodePassword);
        log.debug("已经对密码进行加密处理,原文={},密文={}", rawPassword, encodePassword);
        //为Admin对象的属性赋值:avatar,phone,email,description保持为null
        //为Admin对象的属性赋值:isEnable > 1
        admin.setIsEnable(1);
        //为Admin对象的属性赋值:lastLoginIp > null
        //为Admin对象的属性赋值:lastCount > 0
        admin.setLoginCount(0);
        //为Admin对象的属性赋值:gmtLastLogin > null
        //为Admin对象的属性赋值:gmtCreate,gmtModified > LocalDateTime.now()
        LocalDateTime now = LocalDateTime.now();
        admin.setGmtCreate(now);
        admin.setGmtModified(now);
        //调用AdminMapper对象的int insert(Admin admin)方法插入管理员数据,并获取返回值
        int rows = adminMapper.insert(admin);
        //判断返回值是否不为1
        if (rows != 1) {
            //--抛出ServiceException:服务器忙,请稍后再次尝试
            log.warn("服务器出错了!");
            throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR,"服务器忙,请稍后再次尝试!");
        }

    }
}
